"""
http server for the lpmp project.
"""

import cherrypy
from Collection import *
import simplejson
from string import Template



class lpmp(object):

	# pages stuffs
	def __init__(self):
		self.col = Collection()
		

	def index(self):
		tpl_f = open("templates/main.tpl", "r")
		self.main_template = tpl_f.read()
		return self.main_template
	index.exposed = True


	# JSON stuffs
	def get_artists_JSON(self):
		artists = Artist.select()
		artists = artists.orderBy(Artist.q.name)
		artist_list = []
		for a in artists:
			artist_list.append({"name": str(a.name).replace('"', ''), "id": a.id})
			try:
				print simplejson.dumps( artist_list[ len(artist_list )-1 ])
			except UnicodeDecodeError:
				print "unicode error"
		return simplejson.dumps(artist_list, ensure_ascii=True) 
	get_artists_JSON.exposed = True

	def get_albums_JSON(self, id=None):
		artist = Artist.select(Artist.q.id == id)
		albums = artist[0].albums
		album_list = []
		for a in albums:
			album_list.append({"artist": artist[0].id, "id": a.id, "name": a.name})
			try:
				print simplejson.dumps( album_list[ len(album_list )-1 ])
			except UnicodeDecodeError:
				print "unicode error"
		return simplejson.dumps(album_list, ensure_ascii=True) 
		
	get_albums_JSON.exposed = True

	def test_JSON(self):
		out = "JSON Tests"

	test_JSON.exposed = True

cherrypy.quickstart(lpmp(), "/", "server.config")

